package com.freewater.springboot.demo.aop.pointcuts;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Aspect
public class PointcutBean {

    // 容器中bean名称是"myBean1"的方法进行拦截
    @Pointcut("bean(myBean1)")
    public void pc() {
    }

    @Before("pc()")
    public void m(JoinPoint joinPoint) {
        System.out.println("start " + joinPoint);
    }

    public static class MyBean {

        private final String beanName;

        public MyBean(String beanName) {
            this.beanName = beanName;
        }

        public void m() {
            System.out.println("我是" + this.beanName);
        }
    }

    @Configuration
    @EnableAspectJAutoProxy // 自动生成代理对象
    public static class PointcutBeanConfig {

        // 注入 myBean1
        @Bean("myBean1")
        public MyBean myBean1() {
            return new MyBean("myBean1");
        }

        //  myBean2
        @Bean("myBean2")
        public MyBean myBean2() {
            return new MyBean("myBean2");
        }

        // 注入切面
        @Bean("pointcutBean")
        public PointcutBean pointcutBean() {
            return new PointcutBean();
        }

        public static void main(String[] args) {
            AnnotationConfigApplicationContext context =
                    new AnnotationConfigApplicationContext(PointcutBeanConfig.class);
            MyBean myBean1 = context.getBean("myBean1", MyBean.class);
            myBean1.m();
            MyBean myBean2 = context.getBean("myBean2", MyBean.class);
            myBean2.m();
        }
    }
}
